<template>
  <div class="job-management">
    <!-- 搜索和操作区域：删除“发布状态”筛选项 -->
    <div class="search-operation">
      <el-card shadow="never">
        <div class="search-form">
          <el-form :model="searchForm" inline>
            <el-form-item label="职位标题">
              <el-input v-model="searchForm.title" placeholder="请输入职位标题" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item label="公司名称">
              <el-input v-model="searchForm.company" placeholder="请输入公司名称" clearable style="width: 200px" />
            </el-form-item>
             <el-form-item label="工作地点">
              <el-input v-model="searchForm.location" placeholder="请输入工作地点" clearable style="width: 200px" />
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="handleSearch" :icon="Search">搜索</el-button>
              <el-button @click="handleReset" :icon="Refresh">重置</el-button>
            </el-form-item>
          </el-form>
        </div>
      </el-card>
    </div>

    <!-- 职位列表：删除“状态”列和“上架/下架”操作按钮 -->
    <div class="job-list">
      <el-card shadow="never">
        <template #header>
          <div class="table-header">
            <span>招聘信息列表</span>
            <div>
              <el-button type="primary" @click="handleCreate" :icon="Plus">新增职位</el-button>
              <el-button @click="handleBatchDelete" :icon="Delete" :disabled="selectedIds.length === 0">
                批量删除
              </el-button>
            </div>
          </div>
        </template>

        <el-table :data="jobList" v-loading="loading" border stripe style="width: 100%"
          @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column prop="job_id" label="职位ID" width="100" align="center" />
          <el-table-column prop="title" label="职位标题" min-width="200" show-overflow-tooltip />
          <el-table-column prop="company" label="公司名称" min-width="150" />
          <el-table-column prop="salary_range" label="薪资范围" width="150" />
          <el-table-column prop="location" label="工作地点" width="120" />
          <!-- 移除“状态”列 -->
          <el-table-column prop="created_at" label="发布时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column prop="expires_at" label="截止时间" width="180">
            <template #default="{ row }">
              {{ formatDate(row.expires_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160" fixed="right" align="center">
            <template #default="{ row }">
              <el-button size="small" type="primary" link @click="handleEdit(row)" :icon="Edit">
                编辑
              </el-button>
              <!-- 移除“上架/下架”状态切换按钮 -->
              <el-button size="small" type="danger" link @click="handleDelete(row.job_id)" :icon="Delete">
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>

        <!-- 分页 -->
        <div class="pagination">
          <el-pagination v-model:current-page="pagination.page" v-model:page-size="pagination.pageSize"
            :page-sizes="[10, 20, 50, 100]" :total="pagination.total"
            layout="total, sizes, prev, pager, next, jumper" @size-change="handleSizeChange"
            @current-change="handleCurrentChange" />
        </div>
      </el-card>
    </div>

    <!-- 新增/编辑职位对话框：删除“状态”单选框组 -->
    <el-dialog v-model="formDialogVisible" :title="formTitle" width="700px" destroy-on-close>
      <el-form ref="jobFormRef" :model="jobForm" :rules="jobFormRules" label-width="100px">
        <el-form-item label="职位标题" prop="title">
          <el-input v-model="jobForm.title" placeholder="请输入职位标题" maxlength="100" show-word-limit />
        </el-form-item>
        <el-form-item label="公司名称" prop="company">
          <el-input v-model="jobForm.company" placeholder="请输入公司名称" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="薪资范围" prop="salary_range">
          <el-input v-model="jobForm.salary_range" placeholder="例如：15k-30k" maxlength="20" show-word-limit />
        </el-form-item>
        <el-form-item label="工作地点" prop="location">
          <el-input v-model="jobForm.location" placeholder="请输入工作地点" maxlength="50" show-word-limit />
        </el-form-item>
        <el-form-item label="职位描述" prop="description">
          <el-input v-model="jobForm.description" type="textarea" :rows="4" placeholder="请输入职位描述" 
            maxlength="2000" show-word-limit />
        </el-form-item>
        <el-form-item label="任职要求" prop="requirements">
          <el-input v-model="jobForm.requirements" type="textarea" :rows="4" placeholder="请输入任职要求" 
            maxlength="2000" show-word-limit />
        </el-form-item>
        <el-form-item label="截止时间" prop="expires_at">
          <el-date-picker v-model="jobForm.expires_at" type="date" placeholder="选择截止日期" 
            value-format="YYYY-MM-DD" />
        </el-form-item>
        <!-- 移除“状态”单选框组 -->
      </el-form>
      <template #footer>
        <el-button @click="formDialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit" :loading="formLoading">
          确定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
// 移除状态切换相关图标（View、Promotion）
import {
  Search,
  Refresh,
  Plus,
  Edit,
  Delete
} from '@element-plus/icons-vue'
// API导入：保持原有（若后端也删除状态字段，无需额外调整）
import {
  getJobs,
  createJob,
  updateJob,
  deleteJob,
  batchDeleteJobs
  // 若updateJobAuditStatus未使用，可一并移除
} from '@/api/job';

// 状态管理：删除与status相关的定义
const loading = ref(false)
const formDialogVisible = ref(false)
const formLoading = ref(false)
const jobFormRef = ref()
const currentJob = ref(null)
const jobList = ref([])
const selectedIds = ref([])

// 搜索表单：删除status字段
const searchForm = reactive({
  title: '',
  company: '',
  location: '', // 新增：工作地点搜索值
  dateRange: []
})

// 分页配置
const pagination = reactive({
  page: 1,
  pageSize: 10,
  total: 0
})

// 职位表单：删除status字段
const jobForm = reactive({
  title: '',
  company: '',
  salary_range: '',
  location: '',
  description: '',
  requirements: '',
  expires_at: '' // 移除status字段
})

// 表单验证规则：删除status相关规则
const jobFormRules = {
  title: [
    { required: true, message: '请输入职位标题', trigger: 'blur' },
    { min: 2, max: 100, message: '标题长度在 2 到 100 个字符', trigger: 'blur' }
  ],
  company: [
    { required: true, message: '请输入公司名称', trigger: 'blur' },
    { min: 2, max: 50, message: '公司名称长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  salary_range: [
    { required: true, message: '请输入薪资范围', trigger: 'blur' }
  ],
  location: [
    { required: true, message: '请输入工作地点', trigger: 'blur' }
  ],
  description: [
    { required: true, message: '请输入职位描述', trigger: 'blur' },
    { min: 10, message: '描述至少10个字符', trigger: 'blur' }
  ],
  requirements: [
    { required: true, message: '请输入任职要求', trigger: 'blur' },
    { min: 10, message: '要求至少10个字符', trigger: 'blur' }
  ],
  expires_at: [
    { required: true, message: '请选择截止时间', trigger: 'blur' }
  ]
  // 移除status相关验证规则
}

// 计算属性：无状态相关依赖，保持不变
const formTitle = computed(() => {
  return isCreate.value ? '新增职位' : '编辑职位'
})

const isCreate = computed(() => {
  return !currentJob.value?.job_id
})

// 工具函数：格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    const date = new Date(dateString)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit'
    }).replace(/\//g, '-')
  } catch (error) {
    return dateString
  }
}

// 页面加载时获取职位列表
onMounted(() => {
  fetchJobs()
})

const fetchJobs = async () => {
  try {
    loading.value = true
    const params = {
      page: Number(pagination.page),
      pageSize: Number(pagination.pageSize),
      title: searchForm.title.trim(),
      company: searchForm.company.trim(),
      location: searchForm.location.trim(), // 新增：传递工作地点筛选条件
      startDate: searchForm.dateRange[0] || undefined,
      endDate: searchForm.dateRange[1] || undefined
    }
    console.log('前端传递的筛选参数：', params)

    const response = await getJobs(params)
    console.log('后端返回的完整响应：', response)

    if (response.code === 0) {
      jobList.value = response.data?.list || [] 
      pagination.total = response.data?.total || 0
    } else {
      jobList.value = []
      pagination.total = 0
    }
  } catch (error) {
    jobList.value = []
    pagination.total = 0
  } finally {
    loading.value = false
  }
}

// 搜索按钮点击：确保所有条件生效
const handleSearch = () => {
  // 日期范围校验（可选）
  if (searchForm.dateRange[0] && searchForm.dateRange[1]) {
    const start = new Date(searchForm.dateRange[0])
    const end = new Date(searchForm.dateRange[1])
    if (end < start) {
      ElMessage.warning('结束日期不能早于开始日期')
      return
    }
  }
  
  pagination.page = 1 // 搜索时重置到第一页
  fetchJobs()
}

// 重置按钮：同步清空工作地点
const handleReset = () => {
  searchForm.title = ''
  searchForm.company = ''
  searchForm.location = '' // 新增：重置工作地点
  searchForm.dateRange = []
  pagination.page = 1
  fetchJobs()
}
// 分页处理：逻辑不变
const handleSizeChange = (newSize) => {
  pagination.pageSize = newSize
  pagination.page = 1
  fetchJobs()
}

const handleCurrentChange = (newPage) => {
  pagination.page = newPage
  fetchJobs()
}

// 选择项变化：逻辑不变
const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.job_id)
}

// 新增职位：逻辑不变（表单已无status）
const handleCreate = () => {
  currentJob.value = null
  resetForm()
  formDialogVisible.value = true
}

// 编辑职位：填充表单时移除status字段处理
const handleEdit = async (job) => {
  try {
    currentJob.value = { ...job }
    Object.keys(jobForm).forEach(key => {
      // 仅填充表单中存在的字段（已无status）
      jobForm[key] = currentJob.value[key] || ''
    })
    formDialogVisible.value = true
  } catch (error) {
    ElMessage.error('获取职位详情失败')
    console.error(error)
  }
}

// 移除“切换职位状态”方法（handleToggleStatus）

// 删除单个职位：逻辑不变
const handleDelete = async (jobId) => {
  try {
    await ElMessageBox.confirm(
      '确定要删除这条职位信息吗？删除后不可恢复',
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await deleteJob(jobId)
    if (response.code === 0) {
      ElMessage.success('删除成功')
      fetchJobs()
    } else {
      ElMessage.error(response.msg || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除失败')
      console.error(error)
    }
  }
}

// 批量删除：逻辑不变
const handleBatchDelete = async () => {
  if (selectedIds.value.length === 0) return
  try {
    await ElMessageBox.confirm(
      `确定要删除选中的${selectedIds.value.length}条职位信息吗？删除后不可恢复`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    const response = await batchDeleteJobs(selectedIds.value)
    if (response.code === 0) {
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      fetchJobs()
    } else {
      ElMessage.error(response.msg || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error(error)
    }
  }
}

// 提交表单：表单无status，无需传递该字段
const handleSubmit = async () => {
  try {
    await jobFormRef.value.validate()
    formLoading.value = true
    let response
    if (isCreate.value) {
      // 新增：jobForm已无status字段
      response = await createJob(jobForm)
    } else {
      // 编辑：同样不传递status
      response = await updateJob(currentJob.value.job_id, jobForm)
    }
    if (response.code === 0) {
      ElMessage.success(isCreate.value ? '新增职位成功' : '更新职位成功')
      formDialogVisible.value = false
      fetchJobs()
    } else {
      ElMessage.error(response.msg || (isCreate.value ? '新增失败' : '更新失败'))
    }
  } catch (error) {
    if (error.name !== 'Error') {
      ElMessage.error('请完善表单信息')
    } else {
      ElMessage.error(isCreate.value ? '新增职位失败' : '更新职位失败')
      console.error(error)
    }
  } finally {
    formLoading.value = false
  }
}

// 重置表单：删除status字段重置
const resetForm = () => {
  jobForm.title = ''
  jobForm.company = ''
  jobForm.salary_range = ''
  jobForm.location = ''
  jobForm.description = ''
  jobForm.requirements = ''
  jobForm.expires_at = ''
  // 移除status字段重置

  if (jobFormRef.value) {
    jobFormRef.value.clearValidate()
  }
}
</script>

<style scoped>
.job-management {
  padding: 20px;
}

.search-operation {
  margin-bottom: 20px;
}

.search-form {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.job-list {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}
</style>